package com.xiaoKe.zhonghzu.global.tool;

import com.google.gson.Gson;

import java.lang.reflect.Type;

/**
 * @ProjectName : app
 * @Author : Shijingna
 * @Time : 2022/9/26 10:07 上午
 * @Description : Gson工具类
 */
public class JsonUtils {

    private JsonUtils() {
    }

    /**
     * 对象转换成json字符串
     *
     * @param obj
     * @return
     */
    public static String toJson(Object obj) {
        try {
            Gson gson = new Gson();
            return gson.toJson(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * json字符串转成对象
     *
     * @param str
     * @param type
     * @return
     */
    public static <T> T fromJson(String str, Type type) {
        try {
            Gson gson = new Gson();
            return gson.fromJson(str, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * json字符串转成对象
     *
     * @param str
     * @param type
     * @return
     */
    public static <T> T fromJson(String str, Class<T> type) {
        T t = null;
        try {
            Gson gson = new Gson();
            t = gson.fromJson(str, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

}
